from PIL import Image, ImageDraw, ImageOps


def rounded_rectangle_mask(size, radius):
    """
    创建一个具有给定大小和圆角半径的蒙版。
    """
    mask = Image.new("L", size, 0)  # 'L'表示灰度（黑白）图像
    draw = ImageDraw.Draw(mask)

    # 绘制圆角矩形
    draw.rounded_rectangle([(0, 0), size], radius=radius, fill=255)

    return mask


def create_rounded_image_with_border(image_path, output_path, corner_radius, border_width, border_color):
    """
    裁剪图像并将其转换为具有指定圆角半径和边框的圆角矩形。
    """
    # 打开图像
    image = Image.open(image_path)

    # 创建一个圆角蒙版
    mask = rounded_rectangle_mask(image.size, corner_radius)

    # 使用蒙版裁剪图像
    rounded_image = ImageOps.fit(image, mask.size, centering=(0.5, 0.5))
    rounded_image.putalpha(mask)

    # 创建边框图像
    border_size = (image.width + 2 * border_width, image.height + 2 * border_width)
    border_mask = rounded_rectangle_mask(border_size, corner_radius + border_width)

    # 创建一个带有边框的空白图像
    bordered_image = Image.new("RGBA", border_size, (255, 255, 255, 0))  # 全透明背景
    border_draw = ImageDraw.Draw(bordered_image)

    # 绘制边框
    border_draw.rounded_rectangle([(0, 0), border_size], radius=corner_radius + border_width, outline=border_color,
                                  width=border_width)

    # 将裁剪后的图像粘贴到边框图像的中央
    bordered_image.paste(rounded_image, (border_width, border_width), mask=mask)

    # 将最终图像保存为PNG
    bordered_image.save(output_path, "PNG")


# 示例使用
input_image_path = r"C:\Users\Administrator\Desktop\test.jpg"  # 输入图像的路径
output_image_path = "output_with_border.png"  # 输出图像的路径
corner_radius = 100  # 圆角半径
border_width = 30  # 边框宽度
border_color = (0, 0, 0)  # 边框颜色 (红色)

create_rounded_image_with_border(input_image_path, output_image_path, corner_radius, border_width, border_color)
